<template>
  <el-card>
    <el-form :model="form" inline>
      <el-row>
        <el-col :span="14">
          <el-form-item label="农户所在地：">
            <el-cascader v-model="selectedVillage"
                         :options="villageOptions"
                         clearable
                         :props="props1"
                         @change="handleCascaderChange"
                         style="width: 400px;"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="4">
          <el-form-item label="农户姓名：">
            <el-input v-model="form.name" placeholder="请输入：" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="身份证号">
            <el-input v-model="form.idcard" placeholder="请输入完整身份证号" />
          </el-form-item>
        </el-col>
        <el-form-item >
          <el-button type="primary" @click="SearchClick">查询</el-button>
          <el-button @click="resetClick">重置</el-button>
        </el-form-item>
      </el-row>
    </el-form>
  </el-card>
  <el-card style="height: 400px; margin-top: 20px">
  <div class="table-container" style="display: flex; flex-direction: column;">
    <el-table :data="tableData" stripe border class="center-table" style="margin-top:20px;">
      <!--  <el-table-column type="index" width="80" />-->
      <el-table-column prop="farmerid" label="序号" width="80" />
      <el-table-column prop="name" label="农户姓名" width="120"/>
      <el-table-column prop="idcard" label="身份证号" width="220"/>
      <el-table-column prop="city" label="市" width="95" />
      <el-table-column prop="town" label="县" width="95"/>
      <el-table-column prop="county" label="乡" width="95"/>
      <el-table-column prop="village" label="村" width="120"/>
      <el-table-column
          prop="poorlevel"
          label="贫困等级"
          width="150"
          :show-overflow-tooltip="true"
          :formatter="statusFormatter"/>
      <el-table-column label="操作" >
        <template #default="scope">
          <el-button :icon="Edit"  type="primary" @click="update(scope.$index,scope.row)"></el-button>
          <el-popconfirm title="确认删除?" @confirm="delFarmer">
            <template #reference>
              <el-button :icon="Delete"  type="danger" @click="del(scope.$index,scope.row)"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 弹窗用于编辑 -->
    <el-dialog v-model="dialogFormVisible" title="农户信息编辑" width="500">
      <el-form :model="form1">
        <el-form-item label="农户姓名：" :label-width="formLabelWidth">
          <el-input v-model="form1.name" disabled/>
        </el-form-item>
        <el-form-item label="农户身份证号：" :label-width="formLabelWidth">
          <el-input v-model="form1.idcard" disabled/>
        </el-form-item>
        <el-form-item label="贫困等级：" :label-width="formLabelWidth">
          <el-input v-model="form1.poorlevel" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="updateFarmer">确认</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 分页条 -->
    <div class="page" style="display: flex; justify-content: flex-end;">
      <el-pagination
          :background=true
          v-model:total="totalCount"
          v-model:page-size="form.pageSize"
          :small=false
          :page-sizes="[5, 10, 20, 50]"
          @size-change="handleSizeChange"
          layout="sizes, prev, pager, next, jumper"
          @current-change="changePageNumber" />
    </div>
  </div>
  </el-card>
</template>

<script setup>
import {reactive, ref,onMounted,watch} from 'vue'
import villageData from '@/assets/village.json';
import { searchPage,farmerUpdateService, farmerDelService } from '@/api/farmer'
import { ElMessage } from 'element-plus'
import {Delete, Edit} from "@element-plus/icons-vue";

const tableData = ref([]); // table数据
const dialogVisible = ref(false);

const villageOptions = villageData;
const selectedVillage = ref([]);
var requestData=ref([]);
const totalCount = ref(10);
const props1 = {
  checkStrictly: true,
}
const area_data = () =>{
  request_params.pageNum=form.pageNum
  request_params.pageSize=form.pageSize
  request_params.name = form.name;
  request_params.idcard = form.idcard;
  for (let i=0;i<requestData.value.length;i++){
    switch (i) {
      case 0:
        request_params.city = requestData.value[i]['label']
        break;
      case 1:
        request_params.county = requestData.value[i]['label']
        break;
      case 2:
        request_params.town = requestData.value[i]['label']
        break;
      case 3:
        request_params.village = requestData.value[i]['label']
        break;
    }
  }
}

const statusFormatter = (row, column) => {
  const poorlevel = row.poorlevel;
  if (poorlevel == 0) {
    return '不贫困';
  } else if (poorlevel == 1) {
    return '一般贫困';
  } else if (poorlevel == 2 ) {
    return '中等贫困';
  } else if (poorlevel == 3) {
    return '特殊贫困';
  }
  return '未知贫困等级';
};

const request_params = {
  name:'',
  idcard:'',
  city:'',
  county:'',
  town:'',
  village:'',
  pageNum: 1,
  pageSize: 5
}
const form = reactive({
  name:'',
  idcard: '',
  pageNum: 1,
  pageSize: 5
})
onMounted(() => {
  myPage();
});

const SearchClick=((res)=>{
  console.log(1111)
  console.log(request_params)
  myPage();
});
const handleCascaderChange = (value, selectedLabels) => {
  if(value==null)return;
  requestData.value = value.map((val, index) => ({
    // level: index + 1, // 级数
    // value: val,       // 选中的值
    label: findLabelByValue(val,villageOptions), // 查找并添加对应的label
  }));
  console.log(requestData.value);
};


// 辅助函数：根据value查找label
const findLabelByValue = (targetValue, options) => {
  for (const option of options) {
    if (option.value === targetValue) {
      return option.label;
    }
    if (option.children) {
      const foundLabel = findLabelByValue(targetValue, option.children);
      if (foundLabel) {
        return foundLabel;
      }
    }
  }
  return null;
};



const changePageNumber = (pageNum) => {
  form.pageNum = pageNum;
  myPage();
}

const handleSizeChange = () => {
  myPage();
}

const myPage = () => {
  area_data();
  searchPage(request_params).then((res) => {
    console.log(res)
    tableData.value = res.data.list;
    totalCount.value = res.data.total;
  });
}

//控制编辑对话框
const dialogFormVisible = ref(false)
const formLabelWidth = '150px'
//打开编辑对话框
const form1 = ref([])
const tableData1 = ref([])
const update=(index,row)=>{
  dialogFormVisible.value=true;
  tableData1.value =index
  form1.value =JSON.parse(JSON.stringify(row))
};
//确认编辑
const updateFarmer = async (clickState)=>{
    let result = await farmerUpdateService(form1.value);
    location.reload();
    console.log("Update response:", result);
    ElMessage.success(result.msg ? result.msg : '编辑成功');
    dialogFormVisible.value = false;
  };

const tableData2 = ref([])
//点击删除
var indexa;
const del=(index,row)=>{
  indexa =index
  tableData2.value =JSON.parse(JSON.stringify(row))
};
//删除所
const delFarmer = async (clickState)=>{
  //调用接口
  let result = await farmerDelService(tableData2.value);
  ElMessage.success(result.msg? result.msg:'删除成功');
  tableData.value.splice(indexa,1);
}

const resetClick = () => {
  request_params.pageNum=form.pageNum;
  request_params.pageSize=form.pageSize;
  request_params.name = '';
  request_params.idcard = '';
  request_params.city = '';
  request_params.county = '';
  request_params.town = '';
  request_params.village = '';
  searchPage(request_params).then((res) => {
    console.log(res)
    tableData.value = res.data.list;
    totalCount.value = res.data.total;
  });
}

</script>

<style scoped>

:deep(.center-table td),
:deep(.center-table th) {
  text-align: center !important;
}

.page{
  margin-top:10px;
}
</style>